<?php
namespace app\common\service;

use app\common\model\CustomerModel;
use app\common\model\FinancialRecordsModel;
use think\facade\Db;

class FinanceService
{
    private static function recordTransaction($transactionType, $amount, $category, $paymentMethod, $note, $extra = [])
    {

        $allow_extra = ['customer_id', 'job_id', 'to_uid', 'boyi_uid'];

        foreach ($extra as $key => $value) {
            if (!in_array($key, $allow_extra)) {
                unset($extra[$key]);
            }
        }

        $record = new FinancialRecordsModel();
        $record->transaction_time = time();
        $record->transaction_type = $transactionType;
        $record->amount = $amount;
        $record->category = $category;
        $record->payment_method = $paymentMethod;
        $record->note = $note;
        foreach ($extra as $key => $value) {
            $record->$key = $value;
        }
        $record->save();

        return $record;
    }

    public static function income($amount, $category, $paymentMethod, $note, $extra = [])
    {
        return self::recordTransaction('income', $amount, $category, $paymentMethod, $note, $extra);
    }

    // 记录出账
    public static function expense($amount, $category, $paymentMethod, $note, $extra = [])
    {
        return self::recordTransaction('expense', $amount, $category, $paymentMethod, $note, $extra);
    }



    public static function addCustomerFincal($user, $customer_id, $amount, $transaction_type, $category, $paymentMethod, $note = ''){

        $customer = CustomerModel::find($customer_id);
        if(!$customer){
            throw new \Exception("客户不存在");
        }

        if($transaction_type == '' || !in_array($transaction_type, ['income', 'expense'])){
            throw new \Exception("交易类型有误");
        }

        if($category == ''){
            throw new \Exception("收支分类有误");
        }

        $remain_amount = $customer->amount - $customer->received_amount;
        if($remain_amount < $amount && $transaction_type == 'income'){
            throw new \Exception('该客户目前剩余金额为' . $remain_amount  . '元，不足以收款' . $amount . '元，请确认后重试');
        }
        try {
            Db::startTrans();
            if ($transaction_type == 'income') {
                $customer->received_amount = $customer->received_amount + $amount;
                $customer->save();
                
                self::income($amount, $category, $paymentMethod, $note, ['customer_id' => $customer_id, 'boyi_uid' => $user['id']]);        
            } elseif ($transaction_type == 'expense') {
                $customer->payout_amount = $customer->payout_amount + $amount;
                $customer->save();
                self::expense($amount, $category, $paymentMethod, $note, ['customer_id' => $customer_id, 'boyi_uid' => $user['id']]);        
            }

            Db::commit();    
        } catch (\Throwable $e) {
            throw new \Exception("添加收款记录失败，请重试");
        }


    }
}